//
//  ZYMainTbaBar.swift
//  weibo-Swift
//
//  Created by Apple on 16/7/19.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class ZYMainTbaBar: UITabBar {

//    闭包属性
    var composeCallback:(() -> Void)?
    
//    懒加载按钮
    lazy var composeButton: UIButton = {
      
        let button = UIButton(type: UIButtonType.Custom)
        
//        设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
//        设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
//        添加到tabbar里面
        self.addSubview(button)
//       添加点击时间
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
    let itemCount: Int = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()
//        计算每个按钮的宽度
    let newItemWith = self.frame.width / CGFloat(itemCount)
        
        //        遍历所有的item
//        定义一个索引
        var index = 0
        for item in self.subviews {
//           遍历出cls类型的item
            let cls = NSClassFromString("UITabBarButton")!
            
            if item.isKindOfClass(cls){
                
                item.frame = CGRect(x: CGFloat(index) * newItemWith , y: 0, width: newItemWith , height: self.frame.height)
            
                index++
                
                if index == 2{
                 
                    index++
//                设置加号按钮
                     composeButton.frame = CGRect(x: 2 * newItemWith, y: 0, width: newItemWith, height: self.frame.height)
                    
                }
            }
      
        }
      }
    
    // MARK: - 按钮点击事件
    func  composeClick () {
//        view不能modal出控制器
          self.composeCallback?()
    }

        
   

}
